<?php

namespace App\Admin\Actions\UserAction;

use App\Models\User;
use Brick\Math\RoundingMode;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Actions\RowAction;
use App\Supports\Withdraw\Withdrawer;
use Illuminate\Database\Eloquent\Model;

class TransferGoldBeans extends RowAction
{
	public $name = '风暴金豆增减';

	public function handle(Model $user, Request $request)
	{
		if (!in_array(Admin::user()->id, [1,3])) {
			return $this->response()->error('无权操作')->refresh();
		}

		/**
		 * @var User $user
		 */

		if ($user->is_locked) {
			return $this->response()->error('当前账号已被锁定');
		}

		$symbol = $request->get('symbol', 0);

		if (!in_array($symbol, [1, 2])) {
			return $this->response()->error('请选择增减方式');
		}

		$beans = big_decimal((string)$request->get('beans', 0));

		if ($beans->isLessThanOrEqualTo(0)) {
			return $this->response()->error('请输入增减数量');
		}

		$finalAmount = $beans->toScale(2, RoundingMode::HALF_UP);

		if ($symbol == 1 and $beans->isGreaterThan(0)) {
			account_beans($user)->plusPresentGoldBeans($finalAmount);
		} elseif ($symbol == 2 and $beans->isGreaterThan(0)) {
			account_beans($user)->minusSystemRecall($finalAmount);
		}

		return $this->response()->success('黄金账户增减成功')->refresh();
	}

	public function form()
	{
		$this->radio('symbol', '加/减')
			->options(['1' => '+', '2' => '-'])
			->rules('required')
			->default(2);

		$this->text('beans', '金额')
			->rules('required|numeric|min:0.01');
	}
}
